package com.lxr0860.lxr0860production_test.itemactivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.Utils;
import com.sdk.devicemanager.ICcon;

import java.util.Random;

public class PorintTestActivity extends Activity {

    private TextView mResult;
    private Button mTestbtn;
    private EditText mTestCount;
    private int WRlen = 2048;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("result", true);
                    mIntent.putExtras(bundle);
                    PorintTestActivity.this.setResult(Contants.TEST_ITEM_POINT, mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pointtest);
        initView();
        initEvent();
    }

    private void initEvent() {
        mTestbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int state = ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(1);

                if (state == 0) {
                    ICcon.getInstance().exPowerOn();
                    if (ICcon.getInstance().setPCIBandrate(115200)) {
                        Log.e("point_band", "setBand");
                    }
                    String trim = mTestCount.getText().toString().trim();
                    if (trim != null) {
                        int parseInt = Integer.parseInt(trim);
                        successCount = 0;
                        errorCount = 0;
                        testPorint(parseInt);
                        mTestbtn.setEnabled(false);
                        mTestbtn.setAlpha(0.5f);
                    }
                } else {
                    mResult.setText("上电失败\n通信失败\n下电失败\n测试失败");
                }
            }
        });
    }

    private void initView() {
        mResult = findViewById(R.id.testResult);
        mTestCount = findViewById(R.id.testcount);
        mTestbtn = findViewById(R.id.btn_test);
    }

    private int successCount = 0;
    private int errorCount = 0;
    private int mcount = 0;
    private void testPorint(int count) {

        mcount = count;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mcount > 0) {
                    String randData = randomHexString(WRlen);
                    Log.e("pointSend", randData);
                    int write = ICcon.getInstance().PCI_CommandWrite(randData.length() / 2, Utils.hexToByteArr(randData), 50);
                    Log.e("pointSend", write + "");

                    String string = "";

                    for (int i = 0; i < 2; i++) {
                        byte[] pci_commandRead = ICcon.getInstance().PCI_CommandRead(write/2, 50, 10);
//                        byte[] pci_commandRead = ICcon.getInstance().PCI_CommandRead(50, 20, 10);
                        if (pci_commandRead != null) {
//                            Log.e("response",new String(pci_commandRead));
                            String s = Utils.bytesToString(pci_commandRead).replace(" ", "");
                            Log.e("pointRead"+i, s);
                            string = string + s;
                        }else{
                            Log.e("pointRead"+i, "null");
                        }
                    }
                    Log.e("pointRead2", string);
                    if (randData.equals(string)) {
                        successCount++;
                    } else {
                        errorCount++;
                    }
                    if ((successCount + errorCount) == count) {
                        int state = ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(0);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTestbtn.setEnabled(true);
                                mTestbtn.setAlpha(1);
                                if (state == 0) {
                                    mResult.append("\n下电成功");
                                } else {
                                    mResult.append("\n下电失败");
                                }
                                if (errorCount > 0) {
                                    mResult.append("\n测试失败\n请检查是否插入板卡！！！");
                                } else {
                                    mResult.append("\n测试成功");
                                    Contants.showDailog(PorintTestActivity.this, "测试完成，是否保存", handler, Gravity.TOP);
                                }
                                mcount = 0;
                                mTestbtn.setEnabled(true);
                                mTestbtn.setAlpha(1);
                            }
                        });
                    }
                    mResult.setText("上电成功\n" + "测试次数：" + count + "\n数据大小(字节)：1K" + "\n成功次数：" + successCount + "\n失败次数：" + errorCount);
                    mcount--;
                }
            }
        }).start();
    }

    /**
     * 获取16进制随机数
     *
     * @param len
     * @return
     */
    public static String randomHexString(int len) {
        try {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < len; i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            return result.toString().toUpperCase();

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mcount = 0;
        int state = ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(0);
        ICcon.getInstance().ex3PowerOff();
//        ICcon.oPenOrCloseSerialPort(1,0);
    }
}
